package com.seeyon.apps.hems.kit;

import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.log.CtpLogFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;


public class HttpKit {

    private static final Log log = CtpLogFactory.getLog(HttpKit.class);

    private static PoolingHttpClientConnectionManager cm;
    private static String EMPTY_STR = "";


    private static void init() {
        if (cm == null) {
            cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(50);// 整个连接池最大连接数
            cm.setDefaultMaxPerRoute(5);// 每路由最大连接数，默认值是2
        }
    }

    /**
     * 通过连接池获取HttpClient
     */
    private static CloseableHttpClient getHttpClient() {
        init();
        return HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String getHeader(String url, Map<String, Object> headers)
            throws Exception {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        HttpGet httpGet = new HttpGet(ub.build());
        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }
        return getResult(httpGet);
    }


    /**
     * @param url
     * @param json
     * @return
     * @throws Exception
     */
    public static String post(String url, String json, String tokenId) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        if(!"".equals(tokenId)){
          httpPost.setHeader("token", tokenId);
        }
        if(!"".equals(json)){
            StringEntity entity = new StringEntity(json, "UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
        }
        return getResult(httpPost);
    }

    public static String post(String url, String header) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        if(!"".equals(header)){
            httpPost.setHeader("Cookie", header);
        }
        return getResult(httpPost);
    }

    public static String uploadFile(String pathUrl, File file) {
        try {
            URL preUrl = new URL(pathUrl);
            HttpURLConnection hc = (HttpURLConnection) preUrl.openConnection();
            hc.setDoOutput(true);
            hc.setUseCaches(false);
            hc.setRequestProperty("contentType", "charset=utf-8");
            hc.setRequestMethod("POST");
            hc.setRequestProperty("Content-Type","multipart/form-data;boundary=" + FILE_BOUNDARY);
            DataOutputStream dos = new DataOutputStream(hc.getOutputStream());
            dos.write(getStartData(file));
            BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
            int data = 0;
            while ((data = input.read()) != -1) {
                dos.write(data);
            }
            dos.write(("\r\n--" + FILE_BOUNDARY + "--\r\n").getBytes());
            dos.flush();
            dos.close();
            StringBuffer sb = new StringBuffer();
            InputStream is = hc.getInputStream();
            int ch;
            while ((ch = is.read()) != -1) {
                sb.append((char) ch);
            }
            if (is != null){
                is.close();
            }
            if (input != null){
                input.close();
            }
            return sb.toString();
        } catch (Exception e) {
            log.error("附件上传失败:",e);
        }
        return null;

    }

    /** 分隔符 */
    public static final String FILE_BOUNDARY = "-----";

    /**
     * @param file
     * @return
     */
    private static byte[] getStartData(File file) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append("--");
        sb.append(FILE_BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data; \r\n name=\"1\"; filename=\""
                + file.getName() + "\"\r\n");
        sb.append("Content-Type: image/png\r\n\r\n");
        return sb.toString().getBytes("UTF-8");
    }


    /**
     * 处理Http请求
     *
     * @param request
     * @return
     */
    private static String getResult(HttpRequestBase request) throws Exception {
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity,"UTF-8");//主数据接口 乱码 加响应编码
            response.close();
            return result;
        }
        return EMPTY_STR;
    }

    public static String get(String url) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        return getResult(httpGet);
    }

    /**
     * 处理Http请求
     *
     * @param request
     * @return
     * @throws IOException
     */
    private static File getFileResult(HttpRequestBase request,String fileName) throws IOException {
        CloseableHttpResponse response = null;
        File file = null;
        try {
            CloseableHttpClient httpClient = getHttpClient();
            response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            if (entity != null) {
                String systemUrl = SystemEnvironment.getBaseFolder().replaceAll("\\\\", "/");
                String pathUrl = systemUrl+"/upload/customFile/";
                File filePath = new File(pathUrl);
                if(!filePath.exists()) {
                    createFolder(pathUrl);
                }
                String fileUrl = pathUrl+fileName;
                file = new File(fileUrl);
                FileUtils.copyInputStreamToFile(inputStream, file);
                return file;
            }
        } catch (Exception e) {
            return file;
        }finally {
            if(response != null) {
                response.close();
            }
        }
        return file;

    }
    /**
     * 创建文件夹<br>
     * 目录存在直接返回目录对象，不存在则创建
     *
     * @param path 路径
     * @return 目录对象
     */
    private static File createFolder(String path) {
        File ret = null;
        File file = new File(path);
        if (!file.exists()) {
            if (file.mkdirs()) {
                ret = file;
            }
        } else {
            ret = file;
        }
        return ret;
    }

    public static File getFile(String url,String fileName) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        return getFileResult(httpGet,fileName);
    }


}
